import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import ProTable from '@ant-design/pro-table';
import {SystemDeptTree} from '@/components/system/dept'
import { useEffect, useState, useRef } from 'react';
import { page, removeBatch, lock, unLock } from '@/services/system/user';
import { listAll } from '@/services/system/role';
import { Button, Divider, Tag, message, } from 'antd';
import styles from './index.less';
import { EditOutlined, SafetyOutlined, CloseSquareOutlined, CheckSquareOutlined, LockOutlined } from '@ant-design/icons';
import SystemUserForm from './components/form';
import SystemUserDetail from './components/detail';
import SystemUserPassword from './components/password';
import SystemUserAuth from './components/auth';
import Confirm from '@/components/common/Confirm';
import moment from 'moment';

const SystemUser = () => {
  const actionRef = useRef();

  const [selectedRowKeys, handleSelectedRowKeys] = useState([]);
  const [formVisible, handleFormVisible] = useState(false);
  const [formValues, handleFormValues] = useState({});
  const [passwordVisible, handlePasswordVisible] = useState(false);
  const [roleSelectList, handleRoleSelectList] = useState({});
  const [dept, handleDept] = useState({});
  const [drawerVisible, handleDrawerVisible] = useState(false);
  const [authVisible, handleAuthVisible] = useState(false);

  const lockStatusMap = {
    YES: { color: 'red', text: '已锁定', },
    NO: { color: 'green', text: '未锁定', }
  }

  useEffect(() => {
    const lostData = async () => {
      const result = await listAll();
      return result.data;
    };

    lostData().then((data) =>{
      const roleSelect = {};

      if (data) {
        data.forEach(role => roleSelect[role.id] = {text: role.name} );
      }

      handleRoleSelectList(roleSelect);
    });
  }, []);

  const handleSelectDept = (node) => {
    handleDept(node);
    if (actionRef.current) actionRef.current.reload();
  };

  const handleRemove = () => {
    Confirm.delete({
      content: `<p><span style="color: #f60"> ${selectedRowKeys.length} 位</span> 用户将被删除</p><p>是否继续？</p>`,
      confirm: () => {
        removeBatch(selectedRowKeys).then((result) => {
          if (result.success) {
            if (actionRef.current) actionRef.current.reload();
            message.success('删除成功!');
          } else {
            message.error('删除失败!');
          }
        });
      },
    });
  }

  const handleRaise = () => {
    handleFormValues({});
    handleFormVisible(true);
  }

  const handleModify = (record) => {
    handleFormValues({
      ...record,
      ...{deptId: record.deptList && record.deptList[0] ? record.deptList[0].id : null},
      ...{roleId: record.roleList && record.roleList[0] ? record.roleList[0].id : null},
      ...{dutyId: record.dutyList && record.dutyList[0] ? record.dutyList[0].id : null},
      ...{jobId: record.jobList && record.jobList[0] ? record.jobList[0].id : null},
      ...{birthday: moment(record.birthday, 'YYYY-MM-DD')}
    });
    handleFormVisible(true);
  }

  const handleModifyPassword = (record) => {
    handleFormValues(record);
    handlePasswordVisible(true);
  }

  const handleLock = (record) => {

    Confirm.sure({
      content: `<span style="color: #f60"> 锁定 ${record.name} ?</span> `,
      confirm: () => {
        lock(record.id).then((result) => {
          if (result.success) {
            if (actionRef.current) actionRef.current.reload();
            message.success('锁定用户成功!');
          } else {
            message.error('锁定用户失败!');
          }
        });
      },
    });
  }

  const handleUnLock = (record) => {

    Confirm.sure({
      content: `<span style="color: #f60"> 解锁 ${record.name} ?</span> `,
      confirm: () => {
        unLock(record.id).then((result) => {
          if (result.success) {
            if (actionRef.current) actionRef.current.reload();
            message.success('解锁用户成功!');
          } else {
            message.error('解锁用户失败!');
          }
        });
      },
    });
  }

  const handleDetail = (record) => {
    handleDrawerVisible(true);
    handleFormValues(record);
  }
  
  const handleAuth = (record) => {
    handleFormValues(record);
    handleAuthVisible(true);
  }

  const columns = [
    { title: '真实姓名', dataIndex: 'name', render: (_, record) => <a onClick={() => { handleDetail(record); }}>{_}</a>, },
    { title: '登陆名称', dataIndex: 'username' },
    { title: '手机号', dataIndex: 'mobile' },
    { 
      title: '性别', dataIndex: 'gender', search: false,
      valueEnum: { MAN: { text: '男' }, WOMAN: { text: '女' } }, 
    },
    { 
      title: '出生日期', dataIndex: 'birthday', search: false, 
      render: (_, record) => {
        return moment(_, 'YYYY-MM-DD').format('YYYY-MM-DD');
      }
    },
    // { title: '身份证号', dataIndex: 'idCard', },
    { title: '角色', dataIndex: 'roleList', 
      valueType: 'select',
      valueEnum: roleSelectList,
      render: (_, record) => {
        if (record.isAdmin === 'YES') {
          return ('超级管理员');
        } else {
          const roleName = record.roleList[0].name;
          return (roleName);
        }
      },
    },
    {
      title: '机构', dataIndex: 'deptList', search: false,
      render: (_, record) => {
        const deptName = record.deptList[0].name;
        return (deptName);
      },
    },
    {
      title: '岗位', dataIndex: 'jobList', search: false,
      render: (_, record) => {
        const name = record.jobList && record.jobList[0] ? record.jobList[0].name : '';
        return (name);
      },
    },
    {
      title: '职务', dataIndex: 'dutyList', search: false,
      render: (_, record) => {
        const name = record.dutyList && record.dutyList[0] ? record.dutyList[0].name : '';
        return (name);
      },
    },
    { title: '数据来源', dataIndex: 'sources', search: false },
    { title: '是否锁定', dataIndex: 'isLock', search: false, 
      render: (_, record) => <Tag color={lockStatusMap[record.isLock].color}>{lockStatusMap[record.isLock].text}</Tag>,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return (
          <>
            <a onClick={() => { handleModifyPassword(record); }}> <LockOutlined/> 修改密码 </a>

            {
              record.isAdmin === 'NO' ? (
                <>
                  <Divider type="vertical" />
                  <a onClick={() => { handleModify(record); }}> <EditOutlined/> 修改信息 </a>

                  <Divider type="vertical" />
                  <a onClick={() => { handleAuth(record) }}> <SafetyOutlined /> 授权 </a>

                  <Divider type="vertical" />
                  {
                    record.isLock === 'YES' ? 
                    (<a onClick={() => { handleUnLock(record); }}> <CheckSquareOutlined /> 解锁 </a>) : 
                    (<a onClick={() => { handleLock(record); }}> <CloseSquareOutlined /> 锁定 </a>)
                  }
                </>
              ) : (null)
            }
            
          </>
        );
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle={`${dept === null || !dept.name ? '' : dept.name} 用户信息查询列表`}
        rowKey="id"
        actionRef={actionRef}
        manualRequest={true}
        toolBarRender={() => [
          selectedRowKeys.length > 0 ? <Button onClick={() => { handleRemove(); }}> 删除 </Button> : null,
          <Button type="primary" onClick={() => { handleRaise(); }}> 新建 </Button>,
        ]}
        request={ async (params) => {
          if (dept === null || !dept.id)  return {};

          const response = await page({
            ...params, 
            ...{deptId: dept.id}, 
            ...{roleId: params.roleList ? params.roleList: null}
          });
          return response;
        }}
        columns={columns}
        pagination={{ pageSize: 10 }}
        rowSelection={{
          selectedRowKeys,
          getCheckboxProps: (record) => ({
            disabled: record.id === 1,
            name: record.name,
          }),
          onChange: (selectedRowKeys, selectedRows) => {
            handleSelectedRowKeys(selectedRowKeys);
          },
        }}
        tableRender={(_, dom) => (
          <ProCard split="vertical">
            <ProCard colSpan={4}>
              <SystemDeptTree onSelect={handleSelectDept} />
            </ProCard>
            <ProCard colSpan={20} headerBordered className={styles.userListContainer}>
              {dom}
            </ProCard>
          </ProCard>
        )}
      />

      {
        formVisible && 
        <SystemUserForm 
          onSubmit={() => {
            handleFormVisible(false);
            if (actionRef.current) actionRef.current.reload();
          }}
          onCancel={() => {
            handleFormVisible(false);
          }}
          formVisible={formVisible}
          values={formValues}
        />
      }

      {
        passwordVisible && 
        <SystemUserPassword 
          onCancel={() => {
            handlePasswordVisible(false);
          }}
          formVisible={passwordVisible}
          values={formValues}
        />
      }

      {
        drawerVisible &&
        <SystemUserDetail 
          drawerVisible = {drawerVisible}
          values={formValues}
          onClose={() => {
            handleDrawerVisible(false)
          }}
        />
      }

      {
        authVisible &&
        <SystemUserAuth 
          visible={authVisible}
          values={formValues}
          onClose={() => {
            handleAuthVisible(false);
          }}
        />
      }
    </PageContainer>
  );
};

export default SystemUser;
